package com.kyzh.core.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.gushenge.core.beans.DealProductDetail
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.impls.WealImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.MyApplication
import com.kyzh.core.R

class DealProductDetailViewModel : ViewModel() {

    private val data = MutableLiveData<DealProductDetail>()
    private val error = MutableLiveData<String>()
    private val toast = MutableLiveData<String>()
    private val id = MutableLiveData<String>()
    private val collect = MutableLiveData<Boolean>()

    fun getData(): MutableLiveData<DealProductDetail> {
        if (data.value == null) {
            refresh()
        }
        return data
    }

    fun error(): MutableLiveData<String> {
        return error
    }

    fun toast(): MutableLiveData<String> {
        return toast
    }

    private fun setError(error: String) {
        this.error.value = error
    }

    fun setId(id: String) {
        this.id.value = id
    }

    fun getCollect(): MutableLiveData<Boolean> {
        return collect
    }

    fun refresh() {
        id.value ?: setError(MyApplication.instance.getString(R.string.getDataFailed))
        id.value?.let {
            WealImpl.dealProductDetail(it) {
                success { bean ->
                    (bean as? DealProductDetail)?.apply {
                        data.value = this
                        collect.value = shoucang == 1
                    }
                }
                error { error ->
                    setError(error)
                }
            }
        }
    }

    fun collect() {
        if (getCollect().value == true) {
            UserImpl.collectCancel(getData().value?.shoucang_id ?: "", 2, object : ResultListener {
                override fun success() {
                    collect.value = false
                    toast.value = MyApplication.instance.getString(R.string.collectCancel)
                }

                override fun error(error: String) {
                    toast.value = error
                }
            })
        } else {
            UserImpl.collect(id.value ?: "", 2, object : ResultListener {
                override fun success() {
                    collect.value = true
                    toast.value = MyApplication.instance.getString(R.string.collectSuccess)
                    refresh()
                }

                override fun error(error: String) {
                    toast.value = error
                }
            })
        }
    }
}